import { debugLogger } from '../utils/index.js'

export function behavior(_this, isBehaviorFlag) {
  if (!isBehaviorFlag) {
    if (_this._CONFIG.is_test)
      debugLogger(`config.dataInfo值为false, 跳过数据埋点`);
    return;
  }
  let _b= _this.sendInfo.behavior
  _b.pv = true // 用户浏览页面次数
  _b.pageDuration = true // 页面停留时间
  _b.pageTime.startTime = performance.now()  
  let keyMark = 'dt_monitor';
  ['click', 'touchstart'].forEach(type => {
    window.addEventListener(type, (e) => {
       let path =  composedPath(e)
      const el = getTargetDom(e);
      if (!el) return;
      let flag = isGetClassName(path, keyMark)
      if (flag) {
        const detail = getElementInfo(el);
        _this.sendInfo.behavior.clickList.push(detail)
      }
    }, true)
  });
}

const getElementInfo = (target)=> {
  const tagName = target.tagName.toLowerCase();
  if (tagName === 'body') {
    return '';
  }
  let classNames = target.classList.value;
  const id = target.id ? target.id : '';
  const innerText = target.innerText;
  return {
    id,
    classNames,
    tagName,
    innerText
  }
}
const isGetClassName = (path, mark) => {
  if (path.length > 0) {
    for (let i = 0; i < path.length; i++) {
      if (path[i].classList && Array.from(path[i].classList).length > 0) {
        let i_list = Array.from(path[i].classList)
        if (i_list.includes(mark)) {
         return true
        }   
      }
    } 
  }
}
const  getTargetDom = (e) => {
  const el = document.elementFromPoint(e.pageX, e.pageY);
  if (el) {
    return el 
  }
  return null;
};

const composedPath = e => {
  if (e.path) {
    return e.path;
  }
  let target = e.target;
  e.path = [];
  while (target.parentNode !== null) {
    e.path.push(target);
    target = target.parentNode;
  }
  e.path.push(document, window);
  return e.path;
};






